package com.atguigu.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.exception.YYGHException;
import com.atguigu.yygh.hosp.client.ScheduleFeignClient;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.mq.MqConst;
import com.atguigu.yygh.mq.RabbitService;
import com.atguigu.yygh.order.mapper.OrderInfoMapper;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeiPayService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-04-27
 */
@Service
public class
OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {


    @Autowired
    private ScheduleFeignClient scheduleFeignClient;
    @Autowired
    private PatientFeignClient patientFeignClient;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private WeiPayService weiPayService;

    @Autowired
    private PaymentService paymentService;

    @Override
    public Long saveOrderInfo(String scheduleId, Long patientId) {
        //1.通过scheduleId获取排班数据
        ScheduleOrderVo scheduleOrderVoById = scheduleFeignClient.getScheduleOrderVoById(scheduleId);
        Date stopTime = scheduleOrderVoById.getStopTime();

        if(new DateTime(stopTime).isBeforeNow()){
            throw new YYGHException(2001,"超过了当天挂号截止时间");
        }

        //2.通过patientId获取就诊人数据
        Patient patient = patientFeignClient.getRemotePatientInfo(patientId);

        Map<String,Object> paramMap=new HashMap<String,Object>();
        paramMap.put("hoscode",scheduleOrderVoById.getHoscode());
        paramMap.put("depcode",scheduleOrderVoById.getDepcode());
        paramMap.put("hosScheduleId",scheduleOrderVoById.getHosScheduleId());

        paramMap.put("reserveDate",scheduleOrderVoById.getReserveDate().toString());
        paramMap.put("reserveTime",scheduleOrderVoById.getReserveTime().toString());
        paramMap.put("amount",scheduleOrderVoById.getAmount().toString());



        //3.平台系统请求第三方医院获取第三方医院的返回的数据
        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");

        OrderInfo orderInfo=new OrderInfo();

        if(jsonObject != null && jsonObject.getIntValue("code") == 200){
            //如果第三方医院返回能预约,将上述三部分数据保存到order_info表

            //某个医院某个科室的某个医生的相关信息
            orderInfo.setUserId(patient.getUserId());
            String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);
            orderInfo.setHoscode(scheduleOrderVoById.getHoscode());
            orderInfo.setHosname(scheduleOrderVoById.getHosname());
            orderInfo.setDepcode(scheduleOrderVoById.getDepcode());
            orderInfo.setDepname(scheduleOrderVoById.getDepname());
            orderInfo.setTitle(scheduleOrderVoById.getTitle());
            orderInfo.setScheduleId(scheduleOrderVoById.getHosScheduleId());
            orderInfo.setReserveDate(scheduleOrderVoById.getReserveDate());
            orderInfo.setReserveTime(scheduleOrderVoById.getReserveTime());

            //设置就诊人相关信息
            orderInfo.setPatientId(patient.getId());
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            JSONObject data = jsonObject.getJSONObject("data");
            String hosRecordId = data.getString("hosRecordId");
            int number = data.getIntValue("number");
            String fetchTime = data.getString("fetchTime");
            String fetchAddress = data.getString("fetchAddress");

            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);

            orderInfo.setAmount(scheduleOrderVoById.getAmount());
            orderInfo.setQuitTime(scheduleOrderVoById.getQuitTime());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
            baseMapper.insert(orderInfo);

             //3.2.2 把平台的剩余可预约数更新
            Integer availableNumber = data.getInteger("availableNumber");

            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setAvailableNumber(availableNumber);

            MsmVo msmVo=new MsmVo();
            msmVo.setPhone(patient.getPhone());

            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);

            orderMqVo.setMsmVo(msmVo);


            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);


            //3.2.3 给就诊人发送预约成功的短信提示信息


        }else{
            //3.1 如果第三方医院返回不能预约，这里就抛出异常信息
            throw new YYGHException(2001,"预约失败");
        }


        //4.返回订单id
        return orderInfo.getId();
    }

    @Override
    public Page<OrderInfo> getOrderPage(Integer pageNum, Integer limit, OrderQueryVo orderQueryVo) {

        Page<OrderInfo> page=new Page<OrderInfo>(pageNum,limit);
        QueryWrapper<OrderInfo> queryWrapper=new QueryWrapper<OrderInfo>();
        queryWrapper.eq("user_id",orderQueryVo.getUserId());


        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();

        if(!StringUtils.isEmpty(name)) {
            queryWrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            queryWrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            queryWrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            queryWrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            queryWrapper.ge("create_time",createTimeBegin);
        }

        if(!StringUtils.isEmpty(createTimeEnd)) {
            queryWrapper.le("create_time",createTimeEnd);
        }
        baseMapper.selectPage(page, queryWrapper);
        page.getRecords().parallelStream().forEach(item->{
            this.packageOrderInfo(item);
        });


        return page;
    }

    @Override
    public OrderInfo detail(Long userId, Long orderId) {
        QueryWrapper<OrderInfo> queryWrapper=new QueryWrapper<OrderInfo>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("id",orderId);

        OrderInfo orderInfo = baseMapper.selectOne(queryWrapper);
        this.packageOrderInfo(orderInfo);
        return orderInfo;
    }

    @Override
    public void cancelOrder(Long orderId) {
        //1.先根据订单id查询订单信息


        OrderInfo orderInfo = baseMapper.selectById(orderId);
        //2.1如果此时此刻已经过了取消预约截止时间,抛出异常
        if(new DateTime(orderInfo.getQuitTime()).isBeforeNow()){
            throw new YYGHException(20001,"超过了取消预约的截止时间");
        }

        //1.先判断订单的状态是否为已支付,如果为已支付，就执行退款操作【保存退款记录，更新退款状态】
        if(orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()){
            //执行退款操作
            boolean flag= weiPayService.refund(orderId);
            if(!flag){
                throw new YYGHException(20001,"退款失败");
            }
        }


        //1.更改订单的状态，修改支付记录表的支付状态
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        this.updateById(orderInfo);

        UpdateWrapper<PaymentInfo> updateWrapper=new UpdateWrapper<PaymentInfo>();
        updateWrapper.eq("order_id",orderId);
        updateWrapper.set("payment_status", PaymentStatusEnum.REFUND.getStatus());
        paymentService.update(updateWrapper);



        //2.更新排班剩余可预约数数据：
        OrderMqVo orderMqVo=new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());

        //短信提示
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        orderMqVo.setMsmVo(msmVo);

        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);


    }


    @Override
    public void remind() {
        QueryWrapper<OrderInfo> queryWrapper=new QueryWrapper<OrderInfo>();
        queryWrapper.eq("reserve_date",new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne("order_status",-1);

        List<OrderInfo> orderInfos = baseMapper.selectList(queryWrapper);
        for (OrderInfo orderInfo : orderInfos) {
            MsmVo msmVo=new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");

            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
           rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);

        }
    }


    @Override
    public Map<String, Object> getStatistics(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> statistics = baseMapper.getStatistics(orderCountQueryVo);

        List<String> dateList = statistics.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> countList = statistics.stream().map(OrderCountVo::getCount).collect(Collectors.toList());

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("dateList",dateList);
        map.put("countList",countList);
        return map;
    }

    private void packageOrderInfo(OrderInfo item) {
        Integer orderStatus = item.getOrderStatus();
        String statusNameByStatus = OrderStatusEnum.getStatusNameByStatus(orderStatus);
        item.getParam().put("orderStatusString",statusNameByStatus);
    }
}
